package com.ruoyi.zhifubao.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.ruoyi.zhifubao.domain.AlipayUser;
import com.ruoyi.zhifubao.service.impl.AlipayLoginService;
import com.ruoyi.zhifubao.utils.Constants;
import com.ruoyi.zhifubao.utils.CookieUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;

/**
 * @program: ruoyi
 * @description: 支付宝登录
 * @author: yanghua
 * @create: 2020-09-30 11:45
 **/
@Api(tags = "认证中心")
@RestController
@RequestMapping("/pay")
public class AlipayLoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AlipayLoginController.class);
    @Autowired
    private AlipayLoginService alipayLoginService;

    private TokenEndpoint tokenEndpoint;


    @ApiOperation("OAuth2认证生成token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", defaultValue = "password", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", defaultValue = "client", value = "Oauth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", defaultValue = "123456", value = "Oauth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", defaultValue = "admin", value = "登录用户名"),
            @ApiImplicitParam(name = "password", defaultValue = "123456", value = "登录密码"),

            @ApiImplicitParam(name = "code", value = "小程序code"),
            @ApiImplicitParam(name = "encryptedData", value = "包括敏感数据在内的完整用户信息的加密数据"),
            @ApiImplicitParam(name = "iv", value = "加密算法的初始向量"),
    })
    @PostMapping("/token")
    public void postAccessToken(
            @ApiIgnore Principal principal,
            @ApiIgnore @RequestParam Map<String, String> parameters
    ) throws HttpRequestMethodNotSupportedException {

        parameters.put("grant_type", "authorization_code");
        parameters.put("client_id", "client");
        parameters.put("client_secret", "123456");
        parameters.put("username", "admin");
        parameters.put("password", "123456");
        parameters.put("refresh_token", "authusrB283cb552fdf541db9198c2dc94b97D73");
        parameters.put("code", "26754e1a40e04161ab0c9eeb2da6YX73");
        parameters.put("encryptedData", "");
        parameters.put("iv", "");


        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();


    }
    //===================================================================


    /**
     * 坑：
     * 1支付宝的网关路径，加了dev的是沙箱环境的网关。没加dev的才是生产环境的支付宝网关
     * 2私钥就是一个，但是公钥有2个，一个叫应用公钥，一个是支付宝公钥。而支付宝公钥是在沙箱应用填写应用公钥自动生成的支付宝公钥
     * 而service层需要的公钥是支付宝公钥，不要填错了
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/getAuthInfo")
    public String getAuthCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOGGER.info("支付宝返回信息....................................................");

        //1.获取授权码COde==>从request中获取授权信息
        String authCode = request.getParameter("auth_code");
        String appID = request.getParameter("app_id");
        String scope = request.getParameter("scope");
        LOGGER.info("authCode......" + authCode);

        if (StringUtils.isNotEmpty(authCode)) {
            //2.使用授权码Code获取accessToken
            String accessToken = alipayLoginService.getAccessToken(authCode);
            LOGGER.info("获取access_token = " + accessToken);
            //获取用户信息
            if (StringUtils.isNotEmpty(accessToken)) {
                //3.使用accessToken获取用户信息
                AlipayUser alipayUser = alipayLoginService.getUserInfoByToken(accessToken);
                LOGGER.info("获取用户信息 = " + alipayUser);
                // 4.调用会员服务接口 使用userOpenId 查找是否已经关联过账号
                //ResponseBase openUserBase = memberServiceFegin.findByOpenIdUser(userOpenId);
//                if(openUserBase.getRtnCode().equals(Constants.HTTP_RES_CODE_201)){
//                    // 5.如果没有关联账号，跳转到关联账号页面
//                    httpSession.setAttribute("qqOpenid", userOpenId);
//                    return qqrelation;
//                }
                //6.已经绑定账号  自动登录 将用户token信息存放在cookie中
                setCookie(accessToken, response);
                //跳转至主界面
                response.sendRedirect("http://yincha.com");
            } else {
                request.setAttribute("error", "accessToken为null");
                return "error";
            }
        }

        return "hello alipay!";
    }

    public void setCookie(String memberToken, HttpServletResponse response) {
        CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, memberToken, Constants.COOKIE_TOKEN_MEMBER_TIME);
    }
//    private void thirdPartyLogin(HttpServletRequest request, ThirdPartyUser param) {
//        SysUser sysUser = new SysUser();
//        // 查询是否已经绑定过
////        Long userId = service.queryUserIdByThirdParty(param);
////        //查询并绑定角色
////        if (userId == null) {
////            sysUser =service.insertThirdPartyUser(param);
////        } else {
////            sysUser = service.queryById(param.getId());
////        }
//        sysUser.setUserName("yanghua");
//        sysUser.setPassword("yanghua");
//        String clientIp = (String)request.getSession().getAttribute(Constants.USER_IP);
//        LoginHelper.login(new Login(sysUser.getUserName(), sysUser.getPassword(), false), clientIp);
//    }
}
